package com.biz.primus.ms.commodity.dao.specification;

import com.biz.primus.commodity.vo.backend.GroupProductItemQueryVo;
import com.biz.primus.ms.commodity.dao.po.GroupProductItem;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

public class GroupProductItemSpecification implements Specification<GroupProductItem> {


    private final GroupProductItemQueryVo queryVo;

    public GroupProductItemSpecification(GroupProductItemQueryVo queryVo) {
        this.queryVo = queryVo;
    }

    @Override
    public Predicate toPredicate(Root<GroupProductItem> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = Lists.newArrayList();
        query.orderBy(cb.desc(root.get("createTimestamp")));
        if (StringUtils.isNotBlank(queryVo.getGroupProductCode())) {
            Predicate predicate = cb.equal(root.get("parent").get("product").get("productCode").as(String.class), queryVo.getGroupProductCode());
            predicates.add(predicate);

        }
        if (StringUtils.isNotBlank(queryVo.getProductCode())) {
            Predicate predicate = cb.equal(root.get("product").get("productCode").as(String.class), queryVo.getProductCode());
            predicates.add(predicate);

        }
        if(CollectionUtils.isNotEmpty(predicates)){
            query.where(predicates.toArray(new Predicate[predicates.size()]));
        }
        return query.getRestriction();
    }
}
